package com.xin.web;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.xin.pojo.User;
import com.xin.service.UserService;
import com.xin.service.impl.UserServiceimpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet{
    UserService userService=new UserServiceimpl();
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException{
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        User user = userService.login(new User(null, username, password, null));
        if (user!=null){
            //登录成功后，很多地方都要用户的信息，所有保存在session中，
            //比如登录成功后，显示欢迎某某用户
            req.getSession().setAttribute("user",user);
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
        }else {
            //设置回显
            req.setAttribute("erroratt","用户名或密码错误");
            req.setAttribute("usernameatt",username);
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }
    }
    protected void regist(HttpServletRequest req,HttpServletResponse resp) throws ServletException,
            IOException{
        String username=req.getParameter("username");
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        //获取到图片中的验证码
        String  veCode =(String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //移除session中的验证码信息，防止表单重复提交
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        if (veCode.equalsIgnoreCase(code)){
            if (userService.existsUsername(username)){
                //设置回显信息
                req.setAttribute("erroratt","用户名已存在");
                req.setAttribute("usernameatt",username);
                req.setAttribute("emailatt",email);
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }else {
                userService.registUser(new User(null,username,password,email));
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }
        }else{
            //设置回显信息
            req.setAttribute("erroratt","验证码错误");
            req.setAttribute("usernameatt",username);
            req.setAttribute("emailatt",email);
            req.getRequestDispatcher("pages/user/regist/jsp").forward(req,resp);
        }
    }
    protected void logout(HttpServletRequest req,HttpServletResponse resp) throws ServletException,
            IOException{
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath());
    }
}
